<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/10/26  16:09
 */
namespace app\admin\controller;
class Code extends Common
{
    private $table_admin;

    function __construct()
    {
        parent::__construct();
        $this->table_admin = db('code');
    }

    /*
    代码管理列表
    */
    public function lists()
    {
        $pageParam = ['query' =>[]];
        $where = [];
        $keyword = input('keyword');
        if( $keyword != ''){
            $where['codename'] = array('like','%'.input('keyword').'%');
            $pageParam['query']['keyword'] = $keyword;
            $this->assign('keyword', $keyword);
        }

        $result = $this->table_admin
            ->where($where)
            ->order('id desc')
            ->paginate(15, false, $pageParam);
//        halt($article_result);
        $page  = $result->render();
        $this->assign('page', $page);
        $this->assign('result', $result);

        return $this->fetch();
    }

    //添加
    public function add()
    {
        return $this->fetch('Code/edit');
    }

    public function info()
    {
        $id = input('id');
        $data = $this->table_admin->where(['id'=>$id])->find();
        $this->assign('data', $data);
        return $this->fetch();
    }
    //编辑
    public function edit()
    {
        if(request()->isPost()){
            $id = input('id');
            $type = input('type');
            $introduction = input('introduction');
            $createtime = input('createtime');

            $data['type'] = $type;
            $data['introduction'] = $introduction;
            $data['createtime'] = strtotime($createtime);

            //下载文件上传
            $file = request()->file('file');
            if($file){
                $info = $file->move(ROOT_PATH . 'public/static/uploads');

                if ($info) {
                    $file_path = $info->getSaveName();
                    $getInfo = $info->getInfo();
                    $codename = $getInfo['name'];
                    $data['codename'] = $codename;
                    $data['code_path'] = $file_path;
                    $data['code_size'] = $getInfo['size'];
                }

                //修改逻辑，修改附件，需删除原附件
                if(!empty($id)){
                    $file_path = $this->table_admin->where('id',$id)->value('code_path');
                    $fileurl = ROOT_PATH . 'public/static/uploads/'.$file_path;
                    if(file_exists($fileurl) && !empty($file_path)){
                        unlink($fileurl);
                    }
                }
            }
            if(!$id){
                //添加
                $bool = $this->table_admin->insert($data);
            }else{
                //修改
                $bool = $this->table_admin->where(['id'=>$id])->update($data);
            }

            if($bool){
                $this->success('操作成功', url('Code/lists'));
            }else{
                $this->error('操作失败');
            }

        }
        $id = input('id');
        $this->assign('id', $id);
        $data = $this->table_admin->where(['id'=>$id])->find();
        $data['createtime'] = date('Y-m-d H:i:s', $data['createtime']);
        $this->assign('data', $data);
        return $this->fetch();
    }

    //down下载
    public function down(){
        $id = input('id');
        $data = $this->table_admin->where(['id'=>$id])->find();
        $file_path = IMG_PATH.$data['code_path'];
        if(file_exists($file_path)){
            $this->error('数据包不存在！');
        }

        $file_name_suffix = explode('.', $data['codename']);
        $name = $file_name_suffix[0];

        $fileName = $name ? $name : pathinfo($file_path,PATHINFO_FILENAME);
        $filePath = $file_path;
//halt($file_path);
        $fp = fopen($file_path,'rb');

        if(!$filePath || !$fp){
            header('HTTP/1.1 404 Not Found');
            echo "Error: 404 Not Found.(server file path error)";
            exit;
        }

        $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
        $encoded_filename = urlencode($fileName);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        header('HTTP/1.1 200 OK');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Content-type: application/octet-stream");
        header("Content-Length: ".$data['code_size']);
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".$data['code_size']);

        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }

        ob_end_clean(); //<--有些情况可能需要调用此函数
        // 输出文件内容
        fpassthru($fp);

        exit;
    }

    public function delete()
    {
        $id = input("id");
        if(!$id) $this->error('参数有误');
        $data=$this->table_admin->where("id='$id'")->find();
        if(!$data) $this->error('数据不存在');
        $file = ROOT_PATH . 'public/static/uploads/'.$data['code_path'];
        if($data['code_path'] || is_file($file)){
            unlink($file);
        }
        $res=$this->table_admin->where("id='$id'")->delete();
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!",url('Code/lists'));

    }
}